<?php

// +----------------------------------------------------------------------
//  |  分销管家
// +----------------------------------------------------------------------
//  |  Copyright (c) 2015 http://www.kmeen.com All rights reserved.
// +----------------------------------------------------------------------
//  |  Author: xzake <http://www.kmeen.com>
// +----------------------------------------------------------------------

require_once(APP_PATH . '/Common/Common/text.php');
require_once(APP_PATH . '/Common/Common/time.php');

/**
 * 根据配置类型解析配置
 * @param  string $type  配置类型
 * @param  string  $value 配置值
 * @author xzake
 */
function parse_attr($value, $type) {
    switch ($type) {
        default: //解析"1:1\r\n2:3"格式字符串为数组
            $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
            if (strpos($value, ':')) {
                $value = array();
                foreach ($array as $val) {
                    list($k, $v) = explode(':', $val);
                    $value[$k] = $v;
                }
            } else {
                $value = $array;
            }
            break;
    }
    return $value;
}

/**
 * 检测用户是否登录
 * @return integer 0-未登录，大于0-当前登录用户ID
 * @author xzake
 */
function is_login() {

    return D('User')->isLogin();
}

/**
 * 检测会员是否登录
 * @return integer 0-未登录，大于0-当前登录用户ID
 * @author xzake
 */
function is_login_wechat() {

    return D('Member')->isLogin();
}

/**
 * 系统非常规MD5加密方法
 * @param  string $str 要加密的字符串
 * @return string
 * @author xzake
 */
function user_md5($str, $key = 'KMEEN') {

    return '' === $str ? '' : md5(sha1($str) . $key);
}

/**
 * 根据用户ID获取用户信息
 * @param  integer $id 用户ID
 * @param  string $field
 * @return array  用户信息
 * @author xzake
 */
function get_user_info($id, $field) {

    $userinfo = D('User')->find($id);

    if ($field) {

        return $userinfo[$field];
    }

    return $userinfo;
}

/**
 * 根据会员ID获取用户信息
 * @param  integer $id 用户ID
 * @param  string $field
 * @return array  用户信息
 * @author xzake
 */
function get_user_info_wechat($id, $field = '') {

    $member = D('Member')->find($id);

    $member['info'] = json_decode($member['info'], true);

    if ($field) {

        return $member[$field];
    }

    return $member;
}

/**
 * 获取上传文件路径
 * @param  int $id 文件ID
 * @return string
 * @author xzake
 */
function get_cover($id, $type) {
    $url = D('Upload')->getPath($id);

    if (!$url) {
        switch ($type) {
            case 'avatar' : //用户头像
                $url = C('TMPL_PARSE_STRING.__IMG__') . '/avatar' . rand(1, 7) . '.png';
                break;
            default: //文档列表默认图片
                $url = '/Uploads/default.png';
                break;
        }
    }
    return $url;
}

function get_logo() {
    return get_cover(C("WEB_SITE_LOGO"));
}

/**
 * 系统邮件发送函数
 * @param string $receiver 收件人
 * @param string $subject 邮件主题
 * @param string $body 邮件内容
 * @param string $attachment 附件列表
 * @return boolean
 * @author xzake
 */
function send_mail($receiver, $subject, $body, $attachment) {

    return R('Addons://Email/Email/sendMail', array($receiver, $subject, $body, $attachment));
}

/**
 * 短信发送函数
 * @param string $receiver 接收短信手机号码
 * @param string $body 短信内容
 * @return boolean
 * @author xzake
 */
function send_mobile_message($receiver, $body) {
    return false; //短信功能待开发
}

function order_number_1($fix = 0) {
    static $ORDERSN = array();                                        //静态变量
    $ors = date('y') . strtoupper(dechex(date('m'))) . date('d') .
            substr(time() + $fix + rand(0, 99), -5) . substr(microtime(), 2, 5);     //生成16位数字基本号
    if (isset($ORDERSN[$ors])) {                                    //判断是否有基本订单号
        $ORDERSN[$ors] ++;                                           //如果存在,将值自增1
    } else {
        $ORDERSN[$ors] = 1;
    }
    return $ors . str_pad($ORDERSN[$ors], 2, '0', STR_PAD_LEFT);     //链接字符串
}

function order_number_2($fix = 0) {
    $ors = date('y') . strtoupper(dechex(date('m'))) .
            date('d') . substr(time() + $fix + rand(0, 99), -5) .
            substr(microtime(), 2, 5);     //生成16位数字基本号
    return ($ors );
}

function order_number_3($fix = 0) {
    return date('y') . strtoupper(dechex(date('m'))) . date('d') .
            substr(time() + $fix + rand(0, 99), -5) . substr(microtime(), 2, 5)
            . sprintf('%02d', rand(0, 99));
}

function order_number_4($fix = 0) {
    $year_code = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
    $ia = (intval(date('Y')) - 2005) % 10;
    return $year_code[$ia] . strtoupper(dechex(date('m'))) . date('d') .
            substr(time() + $fix + rand(0, 99), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
}

function log_result($file, $word) {
    $fp = fopen($file, "a");
    flock($fp, LOCK_EX);
    fwrite($fp, "执行日期：" . strftime("%Y-%m-%d-%H：%M：%S", time()) . "\n" . $word . "\n\n");
    flock($fp, LOCK_UN);
    fclose($fp);
}

/**
 * 获取直属人数
 * @param  integer $id 用户ID
 * @param  string $field
 * @return array  用户信息
 * @author xzake
 */
function get_directly_num($id) {

    $count = D('Member')->where("pid=" . $id)->count();
    return $count;
}

function lvl($member) {

    $power = $member['power'];

    $lvl1count = get_directly_num($member['id']);

    $sub = ($member['rgt'] - $member['lft'] - 1) / 2;

    $scale = 0;

    if (($power > 880) && ($sub >= 5000) && ($lvl1count >= 80)) {

        $scale = 100;
    } else if (($power > 880) && ($sub >= 1000) && ($lvl1count >= 50)) {

        $scale = 60;
    } else if (($power > 880) && ($sub >= 300) && ($lvl1count >= 20)) {

        $scale = 40;
    } else if ($power > 880) {

        $scale = 5;
    }

    return $scale;
}

function get_order_status($pay_status, $send_status, $order_status, $divide = " | ") {

    $status = array();

    switch ($pay_status) {
        case '0':
            $status[] = "未支付";
            break;
        case '1':
            $status[] = "未支付";
            break;
        case '2':
            $status[] = "已付款";
            break;
        case '3':
            $status[] = "货到付款";
    }

    switch ($send_status) {
        case '0':
            $status[] = "未发货";
            break;
        case '1':
            $status[] = "已发货";
            break;
        case '2':
            $status[] = "已收货";
            break;
        case '3':
            $status[] = "备货中";
            break;
    }

    switch ($order_status) {
        case '0':
//            $status .= " | 未确认";
            break;
        case '1':
//            $status .= " | 已确认";
            break;
        case '2':
            $status = array();
            $status[] = "已取消";
            break;
        case '3':
            $status = array();
            $status[] = "无效";
            break;
        case '4':
            $status = array();
            $status[] = "申请退货";
            break;
        case '5':
            $status = array();
            $status[] = "已退货";
            break;
    }
    return implode($divide, $status);
}

function get_commission_status($status) {

    $status = "";
    switch ($status) {
        case '0':
            $status[] = "未发放";
            break;
        case '1':
            $status[] = "订单取消";
            break;
        case '2':
            $status[] = "已发放";
            break;
    }
    return $status;
}

/*
 * 获取月份的时间戳
 */

function mFristAndLast($y = "", $m = "") {

    if ($y == "")
        $y = date("Y");
    if ($m == "")
        $m = date("m");

    $m = sprintf("%02d", intval($m));

    $y = str_pad(intval($y), 4, "0", STR_PAD_RIGHT);

    $m > 12 || $m < 1 ? $m = 1 : $m = $m;

    $firstday = strtotime($y . $m . "01000000");

    $firstdaystr = date("Y-m-01", $firstday);

    $lastday = strtotime(date('Y-m-d 23:59:59', strtotime("$firstdaystr +1 month -1 day")));

    return array($firstday, $lastday);
//    return array("firstday" => $firstday, "lastday" => $lastday);
}

/*
 * 获取订单商品名称
 * no 表示订单号
 */

function get_produnct_title($order_no) {
    $ordergoods_model = D('Order');
    $ordergoods_info = $ordergoods_model->where(array('order_no' => $order_no))->getField('title', true);
    foreach ($ordergoods_info as $v) {
        $title += $v . '、';
    }
    $title = substr($title, 0, -1);
    return $title;
}

/*
 * 查询订单ids的商品名称
 * $str 订单商品ids字符串
 */

function check_goods_title($str) {
    if (empty($str)) {
        return null;
    }
    $goods = M('Goods');
    $good_id = explode(',', $str);
    $map['id'] = array('in', $good_id);
    $good_title = $goods->where($map)->getField('title', true);
    $deal = implode('、', $good_title);
    return $deal;
}

/*
 * 保存用户微信头像图片文件
 */

function downloadImageFromWeiXin($url) {
    // 设置运行时间为无限制
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_NOBODY, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $package = curl_exec($ch);
    $httpinfo = curl_getinfo($ch);
    curl_close($ch);
    return array_merge(array('body' => $package), array('header' => $httpinfo));
}

/*
 * 商品库存处理
 * 2016年5月5日 17:01:00
 * $order_info  订单号
 *               @author 行己
 */

function reduce_invertory($order_no) {

    $ordergoods_model = D('OrderGoods');

    $goods_model = D('Goods');

    $map['no'] = array('eq', $order_no);

    $goods_info = $ordergoods_model->where($map)->select();

    foreach ($goods_info as $v) {

        $gmap['id'] = $v['pid'];

        $gcount = $v['count'];

        $good_info = $goods_model->where($gmap)->getField('inventory');

        if ($good_info >= $gcount) {

            $deal = $goods_model->where($gmap)->setDec('inventory', $gcount);
        } else {

            $deal = $goods_model->where($gmap)->setDec('inventory', 1);
        }
    }
}

/*
 * 根据订单id,查询订单商品title
 * @$o_no 订单号
 * @2016年5月13日 11:23:39
 *        @author 行己
 */

function get_order_title($o_no) {

    $map['order_no'] = $o_no;

    $title = M('OrderGoods')->where($map)->getField('title', true);

    $og_title = implode(',', $title);

    return $og_title;
}

/**
 * 
 * 支付完成修改订单
 * 
 * @param order_no 订单号
 * 
 * @param pay_status 默认1 为已支付
 * 
 * @param type 0微信支付 1积分支付
 * 
 */
function update_pay_status($order_no, $data, $type = 0) {

    // 如果这笔订单已经处理过了
    $map['order_no'] = array('eq', $order_no);
    $map['pay_status'] = array('elt', 0);
    $count = M('Order')->where($map)->count();
    if ($count == 0)
        return false;

    // 找出对应的订单
    $order = M('order')->where(array('order_no' => $order_no))->find();

    // 修改支付状态  已支付
    $result = array('pay_status' => 2, 'pay_time' => NOW_TIME, 'pay_result' => json_encode($data));

    if ($type == 1) {

        $result['pay_name'] = '积分支付';

        $setInc_item = 'pay_points';
    } else {

        $result['pay_name'] = '微信支付';

        $setInc_item = 'total_spend';
    }

    M('order')->where(array('order_no' => $order_no))->save($result);

     //完成支付--微信提醒
    $wechat = new \Common\WeChat\Wechat();
    $openid = $data['openid'];
    $content = "您的订单：" . $order['order_no'] . '已支付成功，我们马上给您发货';
    $wechat->sendMsg($openid, $content);

    // 减少对应商品的库存
    minus_stock($order['order_on']);
    //更新用户的累计消费
    M('Member')->where("id = {$order['user_id']}")->setInc($setInc_item, $data['total_fee'] / 100);
    
    return true;
}

/*
  * 减少库存
  */
      function minus_stock($order_no) {
        $goods_list = M()->table('kmeen_order o, kmeen_order_goods og')       
                                                        -> where("o.order_no=og.order_no and o.order_no ='{$order_no}'")
                                                        ->field("og.goods_id")
                                                        ->select();
            foreach ($goods_list as $key => $value) {
                        M('Goods')->where('id='.$value['goods_id']) ->setDec('inventory', 1);                               
            }                        
      }


/*
 * 获取某段时间内的时间戳
 * 
 * @param @num 数字
 * @param type 类型 0 表示day 1表示month 
 * @param status 0表示将来时间  1表示过去时间
 */

function get_time($num = 0, $type = 0, $status = 0) {

    $data = array('min' => '', 'max' => '');

    $today_date = date('Y-m-d', time());

    $today_timestamp = strtotime($today_date);

    switch ($type) {
        case 0:

            if ($status == 0) {

                $get_time = strtotime('+' . $num . 'day', $today_timestamp);
            } else {

                $get_time = strtotime('-' . $num . 'day', $today_timestamp);
            }

            break;
        case 1:

            if ($status == 0) {

                $get_time = strtotime('+' . $num . 'month', $today_timestamp);
            } else {

                $get_time = strtotime('-' . $num . 'month', $today_timestamp);
            }

            break;
    }

    if ($today_timestamp > $get_time) {

        $data['min'] = $get_time;
        $data['max'] = $today_timestamp;
    } else {

        $data['min'] = $today_timestamp;
        $data['max'] = $get_time;
    }

    return $data;
}

/*
 * 处理字符串（添加空格）
 * 
 * str_split 字符串分割成数组
 * 
 * @银行卡号处理
 * 
 */

function rewrite_string($str, $num = 4) {

    $str_arry = str_split($str, $num);

    $deal_str = implode(' ', $str_arry);

    return $deal_str;
}

/*
 * get方式请求url获取返回对象
  */
function get_obj_by_url($url) {
     $data_json= file_get_contents($url);  
      return  json_decode($data_json);
}

/*
 * 获取偶尔不正常用户的信息
  */
  function get_user_by_openid($openid, $access_token='') {
     
        $user_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$openid}&lang=zh_CN";
        $user_info_obj =  get_obj_by_url($user_url);
        
        return $user_info_obj;
  }